package com.mimosa.common.view;

import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mimosa.common.entity.BaseEntity;
import com.mimosa.util.constant.StringConstUtil;

public abstract class EasyUiTreeGrid<T extends BaseEntity> {
	private List<T> list;
	private StringBuilder builder = new StringBuilder();
	/**
	 * 日志记录器
	 */
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public EasyUiTreeGrid(List<T> list) {
		this.list = list;
	}

	protected String[] getColumnNames(T entity) {
		return DataViewHelper.INS.getEntityNames(entity.getClass()
				.getSimpleName());
	}

	void generateDataGrid() {
		this.builder.append("[");
		Object valueObj = null;
		Object valueStr = null;
		for (T t : this.list) {
			this.builder.append("{");
			for (String name : getColumnNames(t)) {
				this.builder.append(StringConstUtil.DOUBLE_QUOTE).append(name)
						.append(StringConstUtil.DOUBLE_QUOTE);
				this.builder.append(StringConstUtil.COLON).append(
						StringConstUtil.DOUBLE_QUOTE);
				try {
					valueObj = PropertyUtils.getNestedProperty(t, name);
				} catch (Exception e) {
					logger.error(
							"can not get entity property value by name : {}",
							name, e);
				}
				if (valueObj instanceof Date) {
					valueStr = DateFormatUtils.ISO_DATE_FORMAT.format(valueObj);
				} else {
					valueStr = ObjectUtils.toString(valueObj);
				}
				this.builder.append(valueStr).append(StringConstUtil.DOUBLE_QUOTE);
				this.builder.append(StringConstUtil.COMMA);
			}
			this.builder.append(StringConstUtil.DOUBLE_QUOTE);
			this.builder.append("state");
			this.builder.append(StringConstUtil.DOUBLE_QUOTE);
			this.builder.append(StringConstUtil.COLON);
			this.builder.append(StringConstUtil.DOUBLE_QUOTE);
			if (this.hasChildren(t)) {
				this.builder.append("closed");
			} else {
				this.builder.append("open");
			}
			this.builder.append(StringConstUtil.DOUBLE_QUOTE);
			this.builder.append("},");
		}

		if (this.list.size() > 0) {
			this.builder.deleteCharAt(this.builder.length() - 1);
		}
		this.builder.append("]");
	}

	/**
	 * 是否有子类信息
	 * 
	 * @param t
	 * @return
	 */
	protected abstract boolean hasChildren(T t);

	public String toString() {
		if (this.builder.length() < 1) {
			generateDataGrid();
		}
		return this.builder.toString();
	}
}
